package com.hroze.util;

import java.util.Map;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.hroze.util.web.Prop;
/**
 * 邮件工具类
 * @author ahoo
 *
 */
public class EmailUtil {
	/**
	 * 配置文件
	 */
	public static Prop config;

	/**
	 * 初始化
	 */
	public static void load() {
		config = new Prop(EmailUtil.class);
	}

	/**
	 * 刷新配置
	 */
	public static void reload() {
		config.reload();
	}

	/**
	 * 填写邮件内容
	 * 
	 * @param email
	 * @param data
	 * @throws EmailException
	 */
	public static void setContent(Email email, Map<String, String> data)
			throws EmailException {
		String type = data.get("type");
		String subject = config.get(type + ".subject");
		String content = config.get(type + ".content");
		subject = OgnlUtil.apply(subject, data);
		content = OgnlUtil.apply(content, data);
		email.setSubject(subject);
		email.setContent(content, Email.TEXT_HTML);
	}

	/**
	 * 发送邮件
	 * 
	 * @param sendTo
	 *            收件人邮箱
	 * @param userName
	 *            收件人名字
	 * @param data
	 *            数据集合
	 * @return 是否发送成功
	 */
	public static boolean send(String sendTo, String userName,
			Map<String, String> data) {
		HtmlEmail email = new HtmlEmail();
		email.setHostName(config.get("host"));
		email.setAuthentication(config.get("user"), config.get("password"));
		try {
			email.addTo(sendTo, userName);
			setContent(email, data);
			email.setFrom(config.get(config.get("from"), config.get("name")));
			email.send();
			return true;
		} catch (EmailException e) {
			System.err.println("邮件发送失败！");
			e.printStackTrace();
			return false;
		}
	}
}
